package com.kgd.news.wxpay.util;

import com.kgd.news.entity.HkopenRecord;
import com.kgd.news.entity.Order;
import com.kgd.news.utils.DateUtils;
import com.kgd.news.wxpay.constant.Constant;

public class GreetingCardUtils {
    /**
     * @param hashb
     * @param issend
     * @param cash_amounts
     * @param orderid      检查订单金额
     * @return
     */
    public static String isOderCashSuccess(String hashb, String issend, String cash_amounts, String orderid) {
//       如果是收到的红包m_order，必须传的
        if (StringUtil.isEmpty(hashb) || StringUtil.isEmpty(issend) || StringUtil.isEmpty(cash_amounts)) {
            return "参数错误，或为空";
        }
        int cash_amounts_int = 0;
        try {
            cash_amounts_int = Integer.parseInt(cash_amounts);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "String转int错误";
        }
//        如果是发送的，判断是否有红包
        if ((Constant.SPLIT_HB_SEND + "").equals(issend)) {
            if ((Constant.GREETCARD_HAS_HB + "").equals(hashb)) {
//核对Order里的金额及状态
                Order order = Order.dao.findFirst("select * from `order` where orderid = ?", orderid);
                if (order != null) {
                    if (order.getState() == Constant.ORDER_STATE_SUCCESS) {
                        if (order.getOrderfee() == cash_amounts_int) {
                            return "SUCCESS";
                        }
                    } else {
                        if (!(order.getOrderfee() == cash_amounts_int)) {
                            return "金额错误";
                        } else if (OrderUtils.checkOrderAndCash(order, cash_amounts_int)) {
//                            由于transationid是收到微信后台付款通知时才拿到的，所以这个一般情况下用不到的
                            //  去微信后台查询这次订单的结果，如果成的话，修改更正数据库等
                            return "SUCCESS";
                        } else {
                            return "未收到微信后台支付信息，请稍后重试";
                        }
                    }
                }
            } else {
                return "SUCCESS";
            }
        } else {
            // TODO: 2018/2/2 以后可以去做，和钱没关系的不是重点
//            如果是收到的,检查split表里的m_order对应的状态金钱
            return "SUCCESS";
        }
        return "未收到微信后台支付信息，请稍后重试";
    }

    /**
     * @param orderid
     * @param userid
     * 记录打开的贺卡
     */
    public static void recordOpenHk(String orderid, String userid,String originuser) {
//        这一句也可以优化的
        HkopenRecord hkopenRecord = HkopenRecord.dao.findFirst("select * from hkopen_record where orderid = ? and  opener = ?", orderid, userid);
        if (hkopenRecord != null) {
//已经打开过了
        } else {
            hkopenRecord = new HkopenRecord();
            hkopenRecord.setOpener(userid);
            hkopenRecord.setOriginuser(originuser);
            hkopenRecord.setOrderid(orderid);
            hkopenRecord.setOpentime(DateUtils.getCurTimessSS());
            hkopenRecord.save();
        }
    }
}
